package com.ohos.apollo_hos.slice;

import com.apollographql.apollo.rxhos.simple.base.BaseModel;
import com.apollographql.apollo.rxhos.simple.base.IModelLisenner;
import com.apollographql.apollo.rxhos.simple.bean.BaseBean;
import com.apollographql.apollo.rxhos.simple.bean.TodoAny;
import com.ohos.apollo_hos.ResourceTable;
import com.ohos.apollo_hos.loading.LoadingUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.miscservices.timeutility.Time;

import java.util.regex.Pattern;

/**
 * 登录页面
 */
public class LoginAbilitySlice extends AbilitySlice {
    private  Button btnCommit;
    private Text errorTipText;
    private TextField tfEmail;
    private Image imgLoading;
    private BaseModel baseModel;
    private int first = 0;
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        baseModel = new BaseModel();
        baseModel.init();
        initLayout();
    }

    private void initLayout() {
        super.setUIContent(ResourceTable.Layout_login_main);
        btnCommit = (Button) findComponentById(ResourceTable.Id_btn_commit);
        errorTipText = (Text) findComponentById(ResourceTable.Id_error_tip_text);
        tfEmail = (TextField) findComponentById(ResourceTable.Id_tf_email);
        imgLoading = (Image) findComponentById(ResourceTable.Id_img_loading);
        btnCommit.setClickedListener(component -> {
            if (match(REGEX_EMAIL, tfEmail.getText())) {
                LoadingUtil.showImageDoadling(imgLoading);
                btnCommit.setVisibility(Component.HIDE);
                baseModel.todo(new TodoAny(0, 0, () -> {
                    Time.sleep(LoadingUtil.WAITING_TIME);
                    return new BaseBean();
                }));
                baseModel.setiModelLisenner(new IModelLisenner() {
                    @Override
                    public void onHosComplete(int flag) {

                    }

                    @Override
                    public void onHosNext(BaseBean bean) {
                        LoadingUtil.hideImageDiading(imgLoading);
                        DatabaseHelper databaseHelper = new DatabaseHelper(getContext()); // context入参类型为ohos.app.Context。
                        Preferences preferences = databaseHelper.getPreferences( "apollo");
                        preferences.putString("email",tfEmail.getText()+"");
                        preferences.flushSync();
                        btnCommit.setVisibility(Component.VISIBLE);
                        onBackPressed();
                    }

                    @Override
                    public void onHosError(int flag, Throwable e) {

                    }
                });
            } else {
                errorTipText.setVisibility(Component.VISIBLE);
                ShapeElement errorElement = new ShapeElement(getContext(), ResourceTable.Graphic_background_text_field_error);
                errorTipText.setBackground(errorElement);
                // TextField失去焦点
                errorTipText.clearFocus();


            }
        });
        tfEmail.setClickedListener(component -> errorTipText.setVisibility(Component.HIDE));
    }


    /**
     * 通用匹配函数
     *
     * @param regex 正则表达式
     * @param input 待校验的字符串
     * @return {@code true} yes, {@code false} no
     */
    public static boolean match(
            final String regex,
            final String input
    ) {
        if (!(input == null || input.length() == 0)) {
            try {
                return Pattern.matches(regex, input);
            } catch (Exception e) {

            }
        }
        return false;
    }
}
